from __future__ import division
import os
import sys
import shutil
import cv2
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET

truePath = "/home/letitia/py-R-FCN/data/VOCdevkit0712/VOC0712/Annotations"
testPath = "/home/letitia/py-R-FCN/data/VOCdevkit0712/VOC0712/xmlfile"
imgPath = "/home/letitia/py-R-FCN/data/VOCdevkit0712/VOC0712/JPEGImages/"
targetpath = "/home/letitia/py-R-FCN/data/VOCdevkit0712/VOC0712/<0.6/"





xmlnames = []
for path,subdir,dirnames in os.walk(testPath):
    for name in dirnames:
        if name.split('.')[1] == "xml":
            xmlnames.append(name)



def readXML(filename):
    objects = []
    tree = ET.parse(filename)
    objs = tree.findall('object')
    for ix, obj in enumerate(objs):
        if obj.find('name').text == 'box':
            bbox = obj.find('bndbox')
            xmin = float(bbox.find('xmin').text)
            ymin = float(bbox.find('ymin').text)
            xmax = float(bbox.find('xmax').text)
            ymax = float(bbox.find('ymax').text)
            objects.append([])
            objects[-1] = [xmin, ymin, xmax, ymax]
    return objects



def show():
    l_objects = []
    t_objects = []

    for path,subdir,dirnames in os.walk(targetpath):
        for name in dirnames:
            if name.split('.')[1] == "jpg":
                xmlname = name.split('.')[0] + ".xml"
                l_objects = readXML(truePath + "/" + xmlname)
                t_objects = readXML(testPath + "/" + xmlname)
                
                im = cv2.imread(imgPath + name)
                fig, ax = plt.subplots(figsize=(12, 12))
                ax.imshow(im, aspect='equal')
                for lob in l_objects:
                    ax.add_patch(
                        plt.Rectangle((lob[0], lob[1]),
                            lob[2] - lob[0],
                            lob[3] - lob[1], fill=False,
                            edgecolor='green', linewidth=3.5)
                        )
                for tob in t_objects:
                    ax.add_patch(
                        plt.Rectangle((tob[0], tob[1]),
                            tob[2] - tob[0],
                            tob[3] - tob[1], fill=False,
                            edgecolor='red', linewidth=3.5)
                        )
                ax.set_title(name,fontsize=14)
                plt.axis('off')
                plt.tight_layout()
                plt.draw()
                plt.show()





ap = 0
label_objects = []
test_objects = []
difficult = []
for name in xmlnames:
    label_objects = readXML(truePath + "/" + name)
    test_objects = readXML(testPath + "/" + name)

    print "~~~~~~~~~~~~~~~~~"
    print name
    #print len(label_objects)
    #print len(test_objects)

    count = 0
    for lob in label_objects:
        for tob in test_objects:
            lw = lob[2] - lob[0]
            lh = lob[3] - lob[1]
            tw = tob[2] - tob[0]
            th = tob[3] - tob[1]
            startX = min(lob[0], tob[0])
            endX = max(lob[2], tob[2])
            startY = min(lob[1], tob[1])
            endY = max(lob[3], tob[3])
            cw = lw + tw - (endX - startX)
            ch = lh + th - (endY - startY)
            if cw <= 0 or ch <= 0:
                continue

            cover = cw * ch
            l_cover = lw * lh
            t_cover = tw * th
            ratio = cover*1./(l_cover + t_cover - cover)

            #if ratio > 0.5 , correct

            if ratio > 0.99:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.95:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.90:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.85:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.80:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.75:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.7:
                count = count+ 1
                test_objects.remove(tob)
                break
            
            elif ratio > 0.65:
                count = count+ 1
                test_objects.remove(tob)
                break
            
            elif ratio > 0.6:
                count = count+ 1
                test_objects.remove(tob)
                break
            
            elif ratio > 0.55:
                count = count+ 1
                test_objects.remove(tob)
                break

            elif ratio > 0.5:
                count = count+ 1
                test_objects.remove(tob)
                break


    s = len(label_objects)

    if s == 0:
        print "??????????????????"
        print count
        print s
    else:
        p = count/s
        print "correct:" + str(p)
        if p < 0.5:
            difficult.append(name)

        ap += p


print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

num = len(xmlnames)
print num
print "map:" + str(ap/num)


for xmlName in difficult:
    imgName = xmlName.split('.')[0] + ".jpg"
    print imgName
    #shutil.copy(imgPath + imgName, targetpath+imgName)

show()